using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.Serialization;

namespace net.notdot.Attercop {
    [Serializable]
    public abstract class UserSettings : ISerializable {
        //TODO: Accept key container name instead
        private CspParameters m_KeyParameters;

        /// <summary>
        /// The parameters for this user's public/private keypair, including where to store it.
        /// </summary>
        public CspParameters KeyParameters
        {
            get
            {
                return m_KeyParameters;
            }
            set
            {
                m_KeyParameters = value;
                m_RSA = new RSACryptoServiceProvider(KeyLength, m_KeyParameters);
                m_RSA.PersistKeyInCsp = true;
            }
        }

        private RSACryptoServiceProvider m_RSA;

        public RSACryptoServiceProvider RSA
        {
            get
            {
                return m_RSA;
            }
        }

        /// <summary>
        /// The length (in bits) of this user's key. Used to generate a new key if one is not found
        /// in the container specified by KeyParamters.
        /// </summary>
        public int KeyLength = 1024;

        /// <summary>
        /// The port to listen on for incoming messages.
        /// </summary>
        public int Port = 1235;

        /// <summary>
        /// The username of this user
        /// </summary>
        public string Nick;

        public UserSettings()
        {
            InitCSP();
        }

        private void InitCSP()
        {
            CspParameters csp = new CspParameters();
            csp.KeyContainerName = "Attercop";
            csp.KeyNumber = 2;
            KeyParameters = csp;
        }


        public Peer Peer {
            get {
                //TODO: Set TotalShared correctly.
                return new Peer(new System.Net.IPEndPoint(System.Net.IPAddress.Any, Port), RSA, Nick, 0);
            }
        }

        //Saves the user settings file to wherever it was loaded from
        public abstract void Save();

        #region ISerializable Members

        protected UserSettings(SerializationInfo info, StreamingContext context)
        {
            KeyLength = info.GetInt32("KeyLength");
            Port = info.GetInt32("Port");
            Nick = info.GetString("Nick");

            InitCSP();
        }

        public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("KeyLength", KeyLength);
            info.AddValue("Port", Port);
            info.AddValue("Nick", Nick);
        }

        #endregion
    }
}
